package com.quan.weixin.common;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mzlion.easyokhttp.HttpClient;
import com.mzlion.easyokhttp.response.HttpResponse;
import com.quan.base.common.utils.RandomUitl;
import com.quan.base.common.utils.SecurityUtils;
import com.quan.weixin.WeixinConstant;

/**
 * 微信工具类
 *
 */
public class WeixinUtil {

	/**
	 * 发送POST请求
	 * @param url 地址
	 * @param obj doPost方法会将数据转换为JSON数据
	 * @return HttpResponse
	 */
	public static HttpResponse doPost(String url, Object obj) {
		return HttpClient.textBody(url).json(obj).execute() ;
	}
	
	/**
	 * 发送POST请求
	 * @param url地址
	 * @param obj doPost方法会将数据转换为JSON数据
	 * @return 返回JSON对象
	 */
	public static JSONObject doPostJSON(String url, Object obj) {
		return JSON.parseObject(HttpClient.textBody(url).json(obj).charset("utf-8").execute().asString()) ;
	}
	
	/**
	 * 发送POST请求
	 * @param url 地址
	 * @param jsonString JSON字符串
	 * @return
	 */
	public static HttpResponse doPostJsonString(String url, String jsonString) {
		return HttpClient.textBody(url).json(jsonString).execute() ;
	}
	
	
	/**
	 * 发生Get请求
	 * @param url
	 * @return HttpResponse
	 */
	public static HttpResponse doGet(String url) {
		return HttpClient.get(url).execute();
	}
	
	
	/**
	 * 微信上传素材的请求方法
	 * @param requestUrl 微信上传临时素材的接口url
	 * @param file 要上传的文件
	 * @return String  上传成功后，微信服务器返回的消息
	 */
	public static String httpRequest(String requestUrl, File file) {  
        StringBuffer buffer = new StringBuffer();  
    
        try{
            //1.建立连接
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  //打开链接
            
            //1.1输入输出设置
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setUseCaches(false); // post方式不能使用缓存
            //1.2设置请求头信息
            httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
            httpUrlConn.setRequestProperty("Charset", "UTF-8");
            //1.3设置边界
            String BOUNDARY = "----------" + System.currentTimeMillis();
            httpUrlConn.setRequestProperty("Content-Type","multipart/form-data; boundary="+ BOUNDARY);

            // 请求正文信息
            // 第一部分：
            //2.将文件头输出到微信服务器
            StringBuilder sb = new StringBuilder();
            sb.append("--"); // 必须多两道线
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length()
                    + "\";filename=\""+ file.getName() + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] head = sb.toString().getBytes("utf-8");
            // 获得输出流
            OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream());
            // 将表头写入输出流中：输出表头
            outputStream.write(head);

            //3.将文件正文部分输出到微信服务器
            // 把文件以流文件的方式 写入到微信服务器中
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                outputStream.write(bufferOut, 0, bytes);
            }
            in.close();
            //4.将结尾部分输出到微信服务器
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
            outputStream.write(foot);
            outputStream.flush();
            outputStream.close();

            
            //5.将微信服务器返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
            
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  

            
        } catch (IOException e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        } 
        return buffer.toString();
    }
	
	/**
	 * 获取微信的JSSDK配置信息
	 * @param request
	 * @return
	 */
	public static Map<String, Object> getJSSDKConfig(HttpServletRequest request) {
		Map<String, Object> configMap = new HashMap<String, Object>() ;
		
		String appId = WeixinConstant.APPID ;
		String jsapi_ticket = WeixinContext.getJsApiTicket() ;
		String timestamp = String.valueOf(System.currentTimeMillis()).substring(0, 10) ;
		String noncestr = RandomUitl.generateString(16) ;
		String requestUrl = request.getHeader("Referer") ;
		
		configMap.put("jsapi_ticket", jsapi_ticket) ;
		configMap.put("noncestr", noncestr) ;
		configMap.put("timestamp", timestamp) ;
		configMap.put("url", requestUrl) ;
		
		String str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+requestUrl ;
		
		String signature = SecurityUtils.sha1(str);  
		
		configMap.put("signature", signature) ;
		configMap.put("appid", appId) ;
		
		return configMap ;
	}
}
